const express = require('express');
const ConnectCas = require('connect-cas2');
const bodyParser = require('body-parser');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const MemoryStore = require('session-memory-store')(session);

const app = express();

app.use(cookieParser());
app.use(session({
    name: 'NSESSIONID',
    secret: 'Hello I am a long long long secret',pwd
    //resave: true,//添加这行
    //saveUninitialized: true,//添加这行
    store: new MemoryStore()  // or other session store
}));

const casClient = new ConnectCas({
    //debug: true,
    ignore: [
        /\/ignore/
    ],
    match: [],
    servicePrefix: 'http://130.51.23.165:3000',
    //servicePrefix: 'http://localhost:3000',
    serverPath: 'http://130.51.23.165:8180',
    paths: {
        validate: '/cas/validate',
        //validate: '/index',
        serviceValidate: '/cas/serviceValidate',
        proxy: '',
        login: '/cas/login',
        logout: '/cas/logout',
        proxyCallback: ''
    },
    redirect: false,
    gateway: false,
    renew: false,
    slo: true,
    cache: {
        enable: false,
        ttl: 5 * 60 * 1000,
        filter: []
    },
    fromAjax: {
        header: 'x-client-ajax',
        status: 418
    }
});

app.use(casClient.core());

// NOTICE: If you want to enable single sign logout, you must use casClient middleware before bodyParser.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.get('/logout', casClient.logout());

// or do some logic yourself
app.get('/logout', function (req, res, next) {
    // Do whatever you like here, then call the logout middleware
    casClient.logout()(req, res, next);
});

app.get('/', function (req, res) {
    // console.log("login.req.session.cas is:")
    // console.log(req.session.cas);

    if (!req.session.cas.user) {
        return next();
    }

    console.log("login.req.session.cas.user is:")
    console.log(req.session.cas.user);

    const username = req.session.cas.user;
    req.session.loggedIn = true;
    req.session.username = username;
    // ...
    //return next();
    // Great, we logged in, now redirect back to the home page.
    //return res.send('<p>You are logged in.</p>');
    return res.send('<p>You are logged in. Your username is ' + req.session.cas.user + '. <a href="/logout">Log Out</a></p>');
});

app.listen(3000);
